<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="1200px" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="120px">
        <!-- 默认cycleType=1，不展示给用户 -->
        <input type="hidden" v-model="formData.cycleType"/>

        <el-row>
          <el-col :span="8">
            <el-form-item label="计划名称" prop="planName">
              <el-input v-model="formData.planName" placeholder="请输入计划名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="巡检类型" prop="planType">
              <el-select v-model="formData.planType" placeholder="请选择巡检类型" style="width: 100%;">
                <el-option v-for="dict in this.getDictDatas(DICT_TYPE.M_PLAN_TYPE)" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="保养周期" prop="maintenanceCycleId">
              <el-select v-model="formData.maintenanceCycleId" placeholder="请选择保养周期" filterable style="width: 100%;">
                <el-option v-for="cycle in maintenanceCycleList" :key="cycle.id" :label="cycle.cycleName" :value="cycle.id"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="所属部门" prop="deptId">
              <treeselect v-model="formData.deptId" :options="deptList" :normalizer="normalizer" placeholder="选择所属部门"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="执行人" prop="executorUserId" >
              <el-select
                v-model="formData.executorUserId"
                placeholder="请选择执行人"
                filterable
                style="width: 100%;"
                remote
                :remote-method="remoteMethod"
              >
                <el-option v-for="user in userList" :key="user.id" :label="user.nickname" :value="user.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所需时间(min)" prop="planUseTime">
              <el-input v-model.number="formData.planUseTime" placeholder="请输入所需时间"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="设备集合" prop="devicesList">
              <el-select
                v-model="formData.devicesList"
                placeholder="请选择设备"
                multiple
                filterable
                remote
                :remote-method="remoteSearchDevice"
                :loading="deviceLoading"
                style="width: 100%;"
                value-key="id"
              >
                <el-option
                  v-for="device in deviceList"
                  :key="device.id"
                  :label="device.deviceName"
                  :value="device.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="描述">
              <Editor v-model="formData.description" :min-height="192"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio v-for="dict in this.getDictDatas(DICT_TYPE.COMMON_STATUS)"
                          :key="dict.value" :label="parseInt(dict.value)">{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as MaintenancePlanApi from '@/api/devices/maintenanceplan/index.js';
import * as MaintenanceCycleApi from '@/api/devices/maintenancecycle';
import * as UserApi from '@/api/system/user';
import * as DeviceApi from '@/api/system/device/index.js'; // 导入设备API
import Editor from '@/components/Editor';
import { getDictDatas, getDictDataLabel, DICT_TYPE } from '@/utils/dict';
import { listDept } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {listUser} from "@/api/system/user";

export default {
  name: "MaintenancePlanForm",
  components: {
    Editor,
    Treeselect
  },
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 部门列表
      deptList: [],
      // 保养周期列表
      maintenanceCycleList: [],
      // 用户列表
      userList: [],
      // 设备列表
      deviceList: [],
      // 设备加载状态
      deviceLoading: false,
      // 表单参数
      formData: {
        id: undefined,
        maintenanceCycleId: undefined,
        cycleType: 1, // 默认值设为1
        planName: undefined,
        planType: undefined,
        cycleCode: undefined,
        cycleName: undefined,
        deptId: undefined,
        deptName: undefined,
        devicesList: [], // 改为数组类型以支持多选
        executorUserId: undefined,
        executorUserName: undefined,
        planUseTime: undefined,
        description: undefined,
        status: 1, // 默认启用
      },
      // 表单校验
      formRules: {
        deptId: [{required: true, message: '所属部门不能为空', trigger: 'blur'}],
        devicesList: [{required: true, message: '设备集合不能为空', trigger: 'blur'}],
        executorUserId: [{required: true, message: '执行人不能为空', trigger: 'blur'}],
        planUseTime: [{required: true, message: '所需时间不能为空', trigger: 'blur'}],
        status: [{required: true, message: '状态不能为空', trigger: 'blur'}],
      },
    };
  },
  methods: {
    normalizer(node) {
      // 构建基础对象，确保包含 id, label, children 属性
      const normalizedNode = {
        id: node.id,
        label: node.name,
        children: node.children,
      };

      // 关键：如果不是第三级节点，则禁用
      if (node.deptType == 3) {
        normalizedNode.isDisabled = true;
      }
      return normalizedNode;
    },

    /** 获取部门列表 */
    async getDeptList() {
      try {
        const response = await listDept();
        this.deptList = this.handleTree(response.data, "id")[0].children;
      } catch (error) {
        console.error('获取部门列表失败', error);
      }
    },

    /** 获取保养周期列表 */
    async getMaintenanceCycleList() {
      try {
        const params = {
          pageNo: 1,
          pageSize: 100,
          cycleType: 1 // 只获取设备类型的保养周期
        };
        const response = await MaintenanceCycleApi.getMaintenanceCyclePage(params);
        this.maintenanceCycleList = response.data.list;
      } catch (error) {
        console.error('获取保养周期列表失败', error);
      }
    },

    /** 获取用户列表 */
    async getUserList() {
      try {
        const params = {
          pageNo: 1,
          pageSize: 20 // 将100改为20，一次只获取20个用户
        };
        const response = await UserApi.listUser(params);
        this.userList = response.data.list;
      } catch (error) {
        console.error('获取用户列表失败', error);
        this.userList = [];
      }
    },

    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;
      this.reset();

      // 加载部门、保养周期和用户列表
      await Promise.all([
        this.getDeptList(),
        this.getMaintenanceCycleList(),
        this.getUserList() // 保持预加载用户列表
      ]);

      // 修改时，设置数据
      if (id) {
        this.formLoading = true;
        try {
          const res = await MaintenancePlanApi.getMaintenancePlan(id);
          this.formData = res.data;
          // 处理设备集合数据，如果是字符串则转换为数组
          if (typeof this.formData.devicesList === 'string') {
            this.formData.devicesList = this.formData.devicesList.split(',').map(id => parseInt(id));
          }
          this.dialogTitle = "编辑设备巡检计划";
        } finally {
          this.formLoading = false;
        }
      } else {
        this.dialogTitle = "新增设备巡检计划";
      }
    },

    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = {...this.formData};

        // 更新执行人名称
        const selectedUser = this.userList.find(user => user.id === data.executorUserId);
        if (selectedUser) {
          data.executorUserName = selectedUser.nickname;
        }

        // 更新周期相关信息
        const selectedCycle = this.maintenanceCycleList.find(cycle => cycle.id === data.maintenanceCycleId);
        if (selectedCycle) {
          data.cycleCode = selectedCycle.cycleCode;
          data.cycleName = selectedCycle.cycleName;
        }


        // 修改的提交
        if (data.id) {
          await MaintenancePlanApi.updateMaintenancePlan(data);
          this.$modal.msgSuccess("修改成功");
        } else {
          // 添加的提交
          await MaintenancePlanApi.createMaintenancePlan(data);
          this.$modal.msgSuccess("新增成功");
        }

        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        maintenanceCycleId: undefined,
        cycleType: 1, // 默认值设为1
        planName: undefined,
        planType: undefined,
        cycleCode: undefined,
        cycleName: undefined,
        deptId: undefined,
        deptName: undefined,
        devicesList: [], // 重置为空数组
        executorUserId: undefined,
        executorUserName: undefined,
        planUseTime: undefined,
        description: undefined,
        status: 1, // 默认启用
      };
      this.resetForm("formRef");
      this.getUserList(); // 重置时也重新获取20个用户
    },

    async remoteMethod(query) {
      if (query !== '') {
        this.userLoading = true;
        try {
          const params = {
            pageNo: 1,
            pageSize: 100, // 远程搜索时保持获取100个结果
            nickname: query
          };
          const response = await UserApi.listUser(params);
          this.userList = response.data.list;
        } catch (error) {
          console.error('搜索用户失败', error);
          this.userList = [];
        } finally {
          this.userLoading = false;
        }
      } else {
        // 当搜索框清空时，重新获取20个用户
        this.getUserList();
      }
    },
    /** 获取设备列表 */
    async getDeviceList(query = '') {
      try {
        this.deviceLoading = true;
        const params = {
          pageNo: 1,
          pageSize: 100,
          deviceName: query,
          deviceCode: query
        };
        const response = await DeviceApi.getDevicePage(params);
        this.deviceList = response.data.list;
      } catch (error) {
        console.error('获取设备列表失败', error);
        this.deviceList = [];
      } finally {
        this.deviceLoading = false;
      }
    },

    /** 设备搜索方法 */
    async remoteSearchDevice(query) {
      await this.getDeviceList(query);
    },

    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;
      this.reset();

      // 加载部门、保养周期和设备列表
      await Promise.all([
        this.getDeptList(),
        this.getMaintenanceCycleList(),
        this.getDeviceList() // 预加载设备列表
      ]);

      // 修改时，设置数据
      if (id) {
        this.formLoading = true;
        try {
          const res = await MaintenancePlanApi.getMaintenancePlan(id);
          this.formData = res.data;
          // 处理设备集合数据，如果是字符串则转换为数组
          this.dialogTitle = "编辑设备巡检计划";
        } finally {
          this.formLoading = false;
        }
      } else {
        this.dialogTitle = "新增设备巡检计划";
      }
    },

    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = {...this.formData};

        // 更新执行人名称
        const selectedUser = this.userList.find(user => user.id === data.executorUserId);
        if (selectedUser) {
          data.executorUserName = selectedUser.nickname;
        }

        // 更新周期相关信息
        const selectedCycle = this.maintenanceCycleList.find(cycle => cycle.id === data.maintenanceCycleId);
        if (selectedCycle) {
          data.cycleCode = selectedCycle.cycleCode;
          data.cycleName = selectedCycle.cycleName;
        }

        // 将设备数组转换为字符串
        // if (Array.isArray(data.devicesList)) {
        //   data.devicesList = data.devicesList.join(',');
        // }

        // 修改的提交
        if (data.id) {
          await MaintenancePlanApi.updateMaintenancePlan(data);
          this.$modal.msgSuccess("修改成功");
        } else {
          // 添加的提交
          await MaintenancePlanApi.createMaintenancePlan(data);
          this.$modal.msgSuccess("新增成功");
        }

        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },
  }
};
</script>

